package com.itheima.interceptor;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import com.itheima.common.utils.BaseContext;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.Date;

@Component
@Log4j2
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    String key="1234";

    /**
     * @param request  current HTTP request
     * @param response current HTTP response
     * @param handler  chosen handler to execute, for type and/or instance evaluation
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
     //  String requestURI = request.getRequestURI();
        //   System.out.println(requestURI);
              //获取token
        String token = request.getHeader("Authorization");
        //判断token是否存在(过期)
        if (null==redisTemplate.hasKey(token)){
            System.out.println("token不存在");
        }
       //校验token
        boolean result = JWT.of(token).setKey(key.getBytes(StandardCharsets.UTF_8)).verify();
        if (!result){
            System.out.println("token不合法");
        }
        //从payload获取id和phone信息
        JWTPayload payload = JWT.of(token).getPayload();
        if (payload==null){
            System.out.println("token载荷没有信息");
        }
        String id = (String) payload.getClaim("id");
        String phone = (String) payload.getClaim("phone");
        //把id放进basecontext
        BaseContext.setCurrentId(id);
        //实现token续签
        redisTemplate.expireAt(token, new Date(System.currentTimeMillis()+60000));
        return true;
    }
}
